<?php

class Controller {
    /*
     * Parametros pasados a la vista
     */

    protected $params;

    public function __construct() {
        if (!empty($_GET["route"]))
            $array = explode('/', ($_GET["route"]));
        if (!empty($array[0]))
            $_REQUEST["controller"] = array_shift($array);
        if (!empty($array[0]))
            $_REQUEST["action"] = array_shift($array);

        if (!empty($_REQUEST["controller"])) {
            $controller = ucfirst($_REQUEST["controller"]) . 'Controller';
            require_once $GLOBALS['controllers_path'] . $controller . '.php';
            new $controller();
        } else {
            $controller = 'IndexController';
            require_once $GLOBALS['controllers_path'] . $controller . '.php';
            new $controller();
        }
    }

    /*
     * Shows the views of the action requested via POST or GET if not especified,
     * if yes then show the $action indicated,
     * $view_path , optional path to the view template file.
     */

    protected function display($action=null, $more_params = null, $layout=null, $view_path = null) {
        if (empty($action)) {
            if (!empty($_REQUEST["action"]))
                $action = $_REQUEST["action"];
            else
                $action="index";
        }
        @extract($this->params);
        unset($this->params);
        ob_start();
        if (empty($view_path)) {
            if ((include_once $GLOBALS['views_path'] . substr(get_class($this), 0, strlen(get_class($this)) - 10) . DIR_SEPARATOR . $action . ".php" ) === false) {
                echo "<h1>View template not found</h1>";
            }
        } else {
            if ((include_once $view_path ) === false) {
                echo "<h1>View template not found</h1>";
            }
        }
        $content_for_layout = ob_get_clean();
        $this->render($content_for_layout, $layout);
    }

    /*
     * Set vars to send to the view.
     */

    protected function set($name, $var) {
        $this->params[$name] = $var;
    }

    /*
     * Render Layout 
     */

    protected function render($content_for_layout, $layout_name=null) {
        if (empty($layout_name))
            include_once $GLOBALS['layouts_path'] . DIR_SEPARATOR . $GLOBALS['layout'] . DIR_SEPARATOR . "layout.php";
        else
            include_once $GLOBALS['layouts_path'] . DIR_SEPARATOR . $layout_name . DIR_SEPARATOR . "layout.php";
    }

}

?>
